package co.yixiang.yshop.module.crm.cloud;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import co.yixiang.yshop.framework.common.exception.ErrorCode;
import co.yixiang.yshop.module.crm.cloud.vo.CallReqVo;
import co.yixiang.yshop.module.crm.cloud.vo.SignOutReqVo;
import lombok.extern.slf4j.Slf4j;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static co.yixiang.yshop.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 容联呼叫中心，地址：https://developer.7moor.com/
 * @author yshop
 */
@Slf4j
public class MoorCloudCall {

    private static final String url = "https://openapis.7moor.com";

    private String accountId;
    private String secret;

    public MoorCloudCall(String accountId,String secret){
        this.accountId = accountId;
        this.secret = secret;
    }

    /**
     * 外呼
     * @param callReqVo
     * @return
     */
    public JSONObject diaLout(CallReqVo callReqVo){
        String formatDateTime = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT);
        String auth = getAuth(formatDateTime);
        String sign = getSig(formatDateTime);

        Map<String,Object> map = new HashMap<>();
        map.put("FromExten",callReqVo.getFromExten());
        map.put("Exten",callReqVo.getExten());
        map.put("ExtenType",callReqVo.getExtenType());

        String newUrl = StrFormatter.format("{}/v20180426/call/dialout/{}?sig={}",url,accountId,sign);

        String res = HttpRequest.post(newUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.AUTHORIZATION,auth)
                .body(JSONUtil.toJsonStr(map))
                //.form(map)
                .timeout(20000)//超时，毫秒
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(res);
        log.info("diaLout-msg:{}",jsonObject);
        if(!Boolean.valueOf(jsonObject.get("Succeed").toString())){
            log.error("呼叫失败：{}",jsonObject.get("Message").toString());
            throw exception(new ErrorCode(202412060,"呼叫失败请联系管理员"));
        }

        return jsonObject;
    }



    /**
     * 签入签出
     * @param signOutReqVo
     * @return
     */
    public JSONObject signInOrOut(SignOutReqVo signOutReqVo){
        String formatDateTime = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT);
        String auth = getAuth(formatDateTime);
        String sign = getSig(formatDateTime);

        Map<String,Object> map = new HashMap<>();
        map.put("sign",signOutReqVo.getSign());
        map.put("Exten",signOutReqVo.getExten());
        map.put("ExtenType",signOutReqVo.getExtenType());

        String newUrl = StrFormatter.format("{}/v20160818/account/SignInOrOut/{}?sig={}",url,accountId,sign);

        String res = HttpRequest.post(newUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.AUTHORIZATION,auth)
                .body(JSONUtil.toJsonStr(map))
                .timeout(20000)//超时，毫秒
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(res);
        log.info("signInOrOut-msg:{}",jsonObject);
        if(!Boolean.valueOf(jsonObject.get("Succeed").toString())){
            log.error("签入签出失败：{}",jsonObject.get("Message").toString());
            throw exception(new ErrorCode(202412061,"呼叫失败请联系管理员"));
        }

        return jsonObject;
    }

    /**
     * 获取通话记录
     * @param starTime
     * @param endTime
     * @return
     */
    public JSONObject getCCCdr(Date starTime,Date endTime){
        String formatDateTime = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_FORMAT);
        String auth = getAuth(formatDateTime);
        String sign = getSig(formatDateTime);

        Map<String,Object> map = new HashMap<>();
        map.put("beginTime",DateUtil.formatDateTime(starTime));
        map.put("endTime",DateUtil.formatDateTime(endTime));

        String newUrl = StrFormatter.format("{}/v20180426/cdr/getCCCdr/{}?sig={}",url,accountId,sign);

        String res = HttpRequest.post(newUrl)
                .header(Header.CONTENT_TYPE, "application/json;charset=utf-8")
                .header(Header.AUTHORIZATION,auth)
                .body(JSONUtil.toJsonStr(map))
                .timeout(20000)//超时，毫秒
                .execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(res);
        log.info("getCCCdr-msg:{}",jsonObject);
        if(!Boolean.valueOf(jsonObject.get("success").toString())){
            log.error("签入签出失败：{}",jsonObject.get("message").toString());
            throw exception(new ErrorCode(202412062,"呼叫失败请联系管理员"));
        }

        return jsonObject;
    }


    private String getSig(String time){
        return DigestUtil.md5Hex(accountId + secret + time).toUpperCase();
    }

    private String getAuth(String time) {
       return Base64.encode(accountId + ":" + time);
    }

}
